/**
 * @param {string} watermarkText 水印文本
 * @returns {HTMLDivElement} 水印 DOM 元素
 */
function createWatermark(watermarkText) {
  const can = document.createElement('canvas');
  const ctx = can.getContext('2d');

  // 增大 canvas 宽高以容纳更长的文本
  can.width = 300;
  can.height = 200;

  // 设置基础字体大小
  let fontSize = 16;

  // 根据文本长度动态调整字体大小
  if (watermarkText.length > 40) {
    fontSize = 12;
  } else if (watermarkText.length > 25) {
    fontSize = 14;
  }

  ctx.font = `${fontSize}px Microsoft YaHei`;
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  ctx.textAlign = 'left';
  ctx.textBaseline = 'middle';
  ctx.rotate(-15 * Math.PI / 180); // 减小旋转角度避免截断

  // 获取当前日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1;
  const day = currentDate.getDate();
  const currentDateString = ` ${year}-${month}-${day}`;

  // 合并水印文本和日期
  const fullText = watermarkText + currentDateString;

  // 文本换行处理（每行最多字符数）
  const maxCharsPerLine = 25;
  const lines = [];
  for (let i = 0; i < fullText.length; i += maxCharsPerLine) {
    lines.push(fullText.substr(i, maxCharsPerLine));
  }

  // 计算垂直居中偏移量
  const lineHeight = fontSize * 1.5;
  const totalHeight = lines.length * lineHeight;
  const startY = can.height / 2 - totalHeight / 2;

  // 绘制多行文本
  lines.forEach((line, index) => {
    ctx.fillText(line, can.width / 20, startY + index * lineHeight);
  });

  const div = document.createElement('div');
  div.style.pointerEvents = 'none';
  div.style.top = '0px';
  div.style.left = '0px';
  div.style.position = 'fixed';
  div.style.zIndex = '100000';
  div.style.width = '100%';
  div.style.height = '100%';
  div.style.background = `url(${can.toDataURL('image/png')}) repeat`;
  return div;
}

// 自定义水印指令
export default {
  bind(el, binding) {
    const { watermarkText } = binding.value;

    const watermarkDiv = createWatermark(watermarkText);
    el.__watermark__ = watermarkDiv;
    document.body.appendChild(watermarkDiv);
  },
  unbind(el) {
    if (el.__watermark__) {
      document.body.removeChild(el.__watermark__);
      delete el.__watermark__;
    }
  }
};
